import { merge, ajax, fixPercent } from '../../helper/helper'
import { indexsData, userListMockData, mockOrderData, visitHistoryData, orderList } from '../static/index'
import _ from 'underscore'
import moment from 'moment'

// import { subscribeDateRange } from '../static/index'
import { postType, dateRange } from '../../static/index'


/**
 * 活动列表
 */
const socialListRenderData = function (dispatch, params, parentCallback) {
    const type = params.type;

    const ajaxData = {
        storeNo: user.storeNo,
        page: params.currentPageIndex + 1,
        size: params.limit,
        filter: 'listdata',
        type
    }

    ajax({
        type: 'GET',
        url: `/admin/api/active`,
        data: ajaxData,
        success: (data) => {
            try { data = JSON.parse(data) } catch (err) { };
            if (data && data.success) {
                dispatch({
                    type: 'render-listdata-table',
                    val: data.result
                })
            } else {

            }
        },
        error: () => {

        }
    })

}

const renderData = function (dispatch, params, parentCallback) {

    const ajaxData = {
        id: params.id,
        filter: 'edit'
    }

    ajax({
        type: 'GET',
        url: `/admin/api/active`,
        data: ajaxData,
        success: (data) => {
            try { data = JSON.parse(data) } catch (err) { };
            if (data && data.success) {
                parentCallback(data.result);
            } else {
            }
        },
        error: () => {
            dispatch({

            })
        }
    })

}

const addData = function (dispatch, params, parentCallback) {

    // 按钮转圈等待创建成功
    dispatch({
        type: 'change-new-contact-loading'
    });

    let ajaxData = {
        params: params
    }

    ajax({
        url: '/admin/api/active',
        type: 'POST',
        data: params,
        dataType: 'json',
        success: (data) => {
            try {
                data = JSON.parse(data);
            } catch (error) {

            }
            dispatch({
                type: 'change-new-contact-loading'
            });
            if (data.success) {
                parentCallback({ success: true, message: '操作成功!' });
            } else {
                parentCallback({ success: false, message: '操作失败，请稍后再试!' });
            }
        },
        error: (data) => {

        }
    });

}

const getGoodslist = function (dispatch, params) {
    ajax({
        type: 'POST',
        url: `/admin/api/goods`,
        data: params,
        dataType: 'json',
        success: (data) => {
            try {
                data = JSON.parse(data)
            } catch (err) { };
            if (data && data.success) {
                dispatch({
                    type: 'render-form-goodslist',
                    val: data.result
                })
            } else {

            }
        },
        error: () => {

        }
    })

}

const getGoodslistById = function (dispatch, params) {
    ajax({
        type: 'POST',
        url: `/admin/api/getGoodlistById`,
        data: params,
        dataType: 'json',
        success: (data) => {
            try {
                data = JSON.parse(data)
            } catch (err) { };
            if (data && data.success) {
                dispatch({
                    type: 'render-form-goodslist',
                    val: data.result
                })
            } else {

            }
        },
        error: () => {

        }
    })

}

const socialListRequest = function (dispatch, params) {
    dispatch({
        type: 'social-list-request',
        val: params
    })
}

const socialListSetOnCheck = function (dispatch, params) {
    dispatch({
        type: 'social-list-set-checked',
        val: params
    })
}
const socialListSetPageIndex = function (dispatch, params) {
    let PageIndex = params.skip / params.limit;
    params.currentPageIndex = PageIndex;
    params.targetPageIndex = PageIndex;
    dispatch({
        type: 'social-list-set-setPageIndex',
        val: PageIndex
    })
}

/**
 *
 * 设置订单表格数据
 * @param {*} dispatch
 * @param {*} params
 */
const orderListSetPageIndex = function (dispatch, params) {
    let PageIndex = params.skip / params.limit;
    params.currentPageIndex = PageIndex;
    params.targetPageIndex = PageIndex;
    dispatch({
        type: 'order-list-set-setPageIndex',
        val: PageIndex
    })
}
const orderListRenderData = function (dispatch, params) {
    ajax({
        type: 'GET',
        url: `/associator/getAllUserOrder`,
        data: {
            page: params.currentPageIndex,
            size: params.limit
        },
        success: (data) => {
            try { data = JSON.parse(data) } catch (err) { };
            if (data && data.success) {
                dispatch({
                    type: 'order-list-render-data',
                    val: data.result
                })
            } else {
                dispatch({
                    type: 'order-list-render-data',
                    val: { total: 0, data: [] }
                })
            }
        },
        error: (result) => {
            dispatch({
                type: 'social-list-render-data',
                val: {
                    data: [],
                    count: 0
                }
            })
        }
    })

    // associator
    // setTimeout(function () {
    //     dispatch({
    //         type: 'order-list-render-data',
    //         val: mockOrderData
    //     });
    // }, 100);

}
const orderListRequest = function (dispatch, params) {
    dispatch({
        type: 'order-list-request',
        val: params
    })
}



const submitAddTag = function (dispatch, params) {
    if (!params.tagName) {
        dispatch({
            type: 'print-preview-error',
            val: '标签名不能为空'
        })
    } else {
        ajax({
            type: 'post',
            url: '/socialcrm/saveWeChatUserTags',
            data: {
                platId: params.platId,
                userId: params.userId,
                tagName: params.tagName
            },
            dataType: 'json',
            success: (data) => {
                try { data = JSON.parse(data) } catch (err) { };
                if (data && data.success) {
                    dispatch({
                        type: 'print-preview-message',
                        val: '添加成功!'
                    })
                    let curTag = {
                        id: data.tag_id,
                        name: params.tagName
                    }
                    dispatch({
                        type: 'push-tag-name-to-data',
                        val: curTag
                    })
                } else {
                    dispatch({
                        type: 'print-preview-error',
                        val: data.error || '标签填写错误，请检查'
                    })
                }
            },
            error: () => {
                dispatch({
                    type: 'print-preview-error',
                    val: '标签添加失败，请稍后再试'
                })
            }
        })
    }
}

const submitAddTagRequest = function (dispatch) {
    dispatch({
        type: 'submit-tag-name-request'
    })
}

const eventListRenderData = function (dispatch, params) {
    dispatch({
        type: 'event-add-event-message-type',
        val: 1
    })
    if (params) {
        ajax({
            type: 'GET',
            url: `/associator/getEvents`,
            data: {
                contactId: params.contactId,
                page: params.page,
                size: params.size
            },
            success: (result) => {
                try { result = JSON.parse(result) } catch (err) { };
                if (result && result.success) {
                    dispatch({
                        type: 'event-list-render-data',
                        val: {
                            data: result.result.data,
                            count: result.result.total,
                        }
                    });
                    if (result.result.total > params.page * params.size) {
                        dispatch({
                            type: 'event-add-event-message-type',
                            val: 3
                        });
                    } else {
                        dispatch({
                            type: 'event-add-event-message-type',
                            val: 2
                        });
                    }
                } else {
                    dispatch({
                        type: 'event-list-render-data',
                        val: {
                            data: [],
                            count: 0,
                        }
                    });
                    dispatch({
                        type: 'event-add-event-message-type',
                        val: 2
                    })
                }
            }
        })
    }

    // setTimeout(function () {
    //     dispatch({
    //         type: 'event-list-render-data',
    //         val: visitHistoryData.result
    //     })
    //     var total = visitHistoryData.result.total;
    //     if (total > params.size) {
    //         dispatch({
    //             type: 'event-add-event-message-type',
    //             val: 3
    //         });
    //     } else {
    //         dispatch({
    //             type: 'event-add-event-message-type',
    //             val: 2
    //         });
    //     }
    // }, 1000);

}
const eventListRequest = function (dispatch, params) {
    dispatch({
        type: 'event-list-request',
        val: params
    })
}
const resetPreviewMessage = function (dispatch) {
    dispatch({
        type: 'print-preview-message',
        val: null
    });

    dispatch({
        type: 'print-preview-error',
        val: null
    });

    history.back()
}
//获取当前日期前n天的日期
const getBeforeDate = function (num) {
    let n = num;
    let d = new Date();
    let year = d.getFullYear();
    let mon = d.getMonth() + 1;
    let day = d.getDate();
    if (day <= n) {
        if (mon > 1) {
            mon = mon - 1;
        }
        else {
            year = year - 1;
            mon = 12;
        }
    }
    d.setDate(d.getDate() - n);
    year = d.getFullYear();
    mon = d.getMonth() + 1;
    day = d.getDate();
    let s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    return s;
}
const selectEventDateRange = function (dispatch, eventDateRangeType, params) {
    dispatch({
        type: 'select-eventdate-range',
        val: eventDateRangeType
    });
    let endTime = moment().format('YYYY-MM-DD'),
        startTime = "";
    switch (eventDateRangeType) {
        case 0:
            startTime = moment().subtract(7, 'days').format('YYYY-MM-DD') + "";
            break;
        case 1:
            startTime = moment().subtract(30, 'days').format('YYYY-MM-DD') + "";
            break;
        case 2:
            startTime = moment().subtract(90, 'days').format('YYYY-MM-DD') + "";
            break;
        case 3:
            return;
    }
    dispatch({
        type: 'select-date',
        startTime: startTime,
        endTime: endTime
    })
}
const changeMoreEventMessageType = function (dispatch, params) {
    if (params.moreEventMessageType == '2') {
        dispatch({
            type: 'set-next-id',
            val: params.cur_next_id
        })
    }
}

// 设置用户基本信息
const initialState = function (dispatch, params) {

    if (params) {
        dispatch({
            type: 'set-user-info',
            val: params
        })
    }
}


// 获取用户交易订单记录
const setUserOrder = function (dispatch, params) {
    // 获取交易订单信息
    dispatch({
        type: 'set-more-user-order',
        val: 1
    });
    ajax({
        url: `/associator/user/order`,
        type: 'GET',
        data: params,
        success: (data) => {
            try {
                var get_data = JSON.parse(data);
            } catch (e) {

            }
            if (get_data.success) {
                dispatch({
                    type: 'set-order-data',
                    val: get_data.result
                });
                if (get_data.result.total > params.page * params.size) {
                    dispatch({
                        type: 'set-more-user-order',
                        val: 3
                    });
                } else {
                    dispatch({
                        type: 'set-more-user-order',
                        val: 2
                    });
                }
            } else {
                dispatch({
                    type: 'set-order-data',
                    val: { total: 0, data: [] }
                });
                dispatch({
                    type: 'set-more-user-order',
                    val: 2
                });
            }
        },
        error: () => {
            dispatch({
                type: 'set-order-data',
                val: { total: 0, data: [] }
            });
            dispatch({
                type: 'set-more-user-order',
                val: 2
            });
        }
    });
}


const setUserId = function (dispatch, params) {
    dispatch({
        type: 'set-user-id',
        val: params
    })
}
const deleteTag = function (dispatch, params) {
    if (!params) {
        console.log('tagId is null!!!!!!!!')
    } else {
        ajax({
            type: 'post',
            url: '/socialcrm/deleteWeChatUserTags',
            data: {
                platId: params.platId,
                userId: params.userId,
                tagId: params.tagId
            },
            dataType: 'json',
            success: (data) => {
                try { data = JSON.parse(data) } catch (err) { };
                if (data && data.success) {
                    dispatch({
                        type: 'print-preview-message',
                        val: '删除标签成功!'
                    })
                    dispatch({
                        type: 'delete-tag-from-data',
                        val: params.tagId
                    })
                } else {
                    dispatch({
                        type: 'print-preview-message',
                        val: data.error || '删除标签失败!请稍后再试'
                    })

                }
            },
            error: () => {
                dispatch({
                    type: 'print-preview-message',
                    val: '删除标签失败!请稍后再试'
                })
            }
        })
    }
}
const updateMetaDataLifeCycle = function (dispatch, params) {
    if (!params) {
        console.log('life cycle id is null!!!!!!!!')
    } else {
        ajax({
            type: 'post',
            url: '/socialcrm/updateMetaDataLifeCycle',
            data: params,
            dataType: 'json',
            success: (data) => {
                try { data = JSON.parse(data) } catch (err) { };
                if (data && data.success) {

                } else {
                    dispatch({
                        type: 'print-preview-error',
                        val: data.error || '更改失败，请稍后重试！'
                    })
                }
            },
            error: () => {
                dispatch({
                    type: 'print-preview-error',
                    val: '更改失败，请稍后重试！'
                })
            }
        })
    }
}

const optionsRun = function (dispatch, index, menuId) {
    switch (menuId) {
        case 1:

        case 2:
            dispatch({
                type: 'set-selector-post-type',
                val: index
            })
            break;
        case 3: case 4: case 5: case 6: case 7:
            dispatch({
                type: 'set-selector-post-type1',
                val: index
            })
            break;
        case 8: case 9: case 10: case 11:
            dispatch({
                type: 'set-selector-post-type2',
                val: index
            })
            break;
        default:
            dispatch({
                type: 'set-selector-post-type2',
                val: index
            })
            break;
    }
}

const saveUserInfo = function (dispatch, params, parentCallback) {
    ajax({
        url: '/save/userInfo',
        type: 'POST',
        data: params,
        dataType: 'json',
        success: (data) => {
            try {
                var get_data = JSON.parse(data);
            } catch (error) {

            }
            if (get_data.success) {
                parentCallback({
                    status: true,
                    message: '修改成功!'
                });
            } else {
                parentCallback({
                    status: false,
                    message: '修改失败，请稍后再试!'
                });
            }

        },
        error: () => {
            dispatch({
                type: 'set-user-info',
                val: params
            });
        }
    });
}


const getVisit = (dispatch, now) => {
    ajax({
        url: '/retail/getVisit',
        type: 'GET',
        data: { now },
        success: function (data) {
            var d = JSON.parse(data);
            if (d.success && d.result.data.length) {
                dispatch({
                    type: 'set-visit-number',
                    val: d.result
                });
                dispatch({
                    type: 'set-get-visit-time',
                    val: d.result.data[d.result.data.length - 1].msec
                });

            } else {
                dispatch({
                    type: 'set-visit-number',
                    val: { total: 0, data: [] }
                });
            }
        }
    });


    // dispatch({
    //     type: 'set-visit-number',
    //     val: userListMockData
    // });
    // dispatch({
    //     type: 'set-get-visit-time',
    //     val: userListMockData.data[userListMockData.data.length - 1].msec
    // });

}

/**
 *
 * 设置订单和用户关联起来
 * @param {*} dispatch
 * @param {*} params
 */
const confirmLinkUserOrder = function (dispatch, params) {
    ajax({
        url: '/associator/linkUserOrder',
        type: 'POST',
        dataType: 'json',
        data: params,
        success: function (data) {
            var d = JSON.parse(data);
            if (d.success) {
                dispatch({
                    type: 'refresh-deal-list'
                });
                dispatch({
                    type: 'close-link-order'
                });
            }

        },
        error: (data) => {

        }
    });
}

const searchMethod = function (dispatch, type, keyword) {
    var params = {};
    if (type == 'user') {
        dispatch({
            type: 'change-fetching-status'
        });
        params = {
            page: 1,
            size: 10,
            keyword
        }
    }
    ajax({
        url: `/settings/search/${type}`,
        type: 'GET',
        data: params,
        success: (data) => {
            try {
                data = JSON.parse(data);
            } catch (error) {

            }

            if (data.success) {
                if (type == 'size') {
                    dispatch({
                        type: 'set-all-size',
                        val: data.result.data
                    });
                } else {
                    dispatch({
                        type: 'set-all-clerk',
                        val: data.result.data
                    });
                }
            } else {
                if (type == 'size') {
                    dispatch({
                        type: 'set-all-size',
                        val: []
                    });
                } else {
                    dispatch({
                        type: 'set-all-clerk',
                        val: []
                    });
                }
            }
        },
        error: (data) => {

        }
    });
}

const createNewContact = function (dispatch, contact, parentCallback) {
    // 按钮转圈等待创建成功
    dispatch({
        type: 'change-new-contact-loading'
    });
    // 新增VIP 需要传customerId为-1，contactId 为空字符串 ''
    contact.customerId = -1;
    contact.contactId = '';
    ajax({
        url: '/associator/list/contact',
        type: 'POST',
        data: contact,
        dataType: 'json',
        success: (data) => {
            try {
                data = JSON.parse(data);
            } catch (error) {

            }
            dispatch({
                type: 'change-new-contact-loading'
            });
            if (data.success) {
                parentCallback({ success: true, message: '新增VIP成功!' });
            } else {
                parentCallback({ success: false, message: '新增VIP失败，请稍后再试!' });
            }
        },
        error: (data) => {

        }
    });
}


export const actions = {
    socialListRenderData: socialListRenderData,
    renderData: renderData,
    addData: addData,
    getGoodslist: getGoodslist,
    socialListRequest: socialListRequest,
    socialListSetOnCheck: socialListSetOnCheck,
    socialListSetPageIndex: socialListSetPageIndex,
    submitAddTag: submitAddTag,
    submitAddTagRequest: submitAddTagRequest,
    eventListRenderData: eventListRenderData,
    eventListRequest: eventListRequest,
    resetPreviewMessage: resetPreviewMessage,
    selectEventDateRange: selectEventDateRange,
    changeMoreEventMessageType: changeMoreEventMessageType,
    initialState: initialState,
    setUserId: setUserId,
    deleteTag: deleteTag,
    updateMetaDataLifeCycle: updateMetaDataLifeCycle,
    optionsRun: optionsRun,
    saveUserInfo: saveUserInfo,
    getVisit: getVisit,
    setUserOrder: setUserOrder,
    orderListSetPageIndex: orderListSetPageIndex,
    orderListRenderData: orderListRenderData,
    orderListRequest: orderListRequest,
    confirmLinkUserOrder: confirmLinkUserOrder,
    searchMethod: searchMethod,
    createNewContact: createNewContact,


}